/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;

/**
 *
 * @author Alexx
 */
import engine.Player;
import engine.Singleton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
import json.Protocol;
import org.json.simple.parser.ParseException;

public class ServeOneThread extends Thread implements Server
{
  
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    public Player p;
   // private String login = null;
    //public Protocol p;
    
    
    public ServeOneThread() throws IOException
    {
    }
    
    public ServeOneThread(Socket s) throws IOException
    {
        socket = s;
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                .getOutputStream())), true);
        p = new Player(this);
        Singleton.clients.add(p); 
        
        start();
    }
    
      
    public void sendUser(String send, int newPos)
    {
       out.println(send);
    }
    
    public Player getPlayer(int pos)
    {
      return p;
    }
    
        
    
    public void run()
    {
        try
        {
            while (true)
            {
                String str = in.readLine();

                    
                System.out.println("Server comming: " + str);
                
        try
        {
          new Protocol().get(str, this);
        } catch (ParseException ex)
        {
          Logger.getLogger(ServeOneThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        
              if (str.equals("{\"Type\": \"End\"}")) // тут имя клиента
              {
               // Singleton.getInstance().delUser(login);
                out.println("{\"Type\": \"End\"}");
                break;
              }
                if(str.length() > 1){
                   str = "";
                }
            }
            System.out.println("closing...");
        }
        catch (IOException e)
        {
            System.err.println("IO Exception");
        }
        finally
        {
            try
            {
                socket.close();
            }
            catch (IOException e)
            {
                System.err.println("Socket not closed");
            }
        }
    }

  @Override
  public int getPos()
  {
    return 0;
  }
    
    
}
